<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="../../resources/run-after-layout-and-paint.js"></script>
</head>
<body onload="start();">
<canvas id="webgl" width="200" height="200"></canvas>
<script>
/*
 * crbug.com/438986
 * window.createImageBitmap(HTMLCanvasElement) copies the back buffer of WebGL.
 * So createImageBitmap(HTMLCanvasElement) must create transparent ImageBuffer
 * 1 frame after WebGL draws contents.
 */
    window.jsTestIsAsync = true;

    var canvas = document.createElement("canvas");
    canvas.width = 200;
    canvas.height = 200;
    var ctx = canvas.getContext("2d");
    function shouldBeGreen(x, y) {
        d = ctx.getImageData(x, y, 1, 1).data;
        shouldBeTrue("d[0] == 0");
        shouldBeTrue("d[1] == 255");
        shouldBeTrue("d[2] == 0");
        shouldBeTrue("d[3] == 255");
    }

    function shouldBeTransparent(x, y) {
        d = ctx.getImageData(x, y, 1, 1).data;
        shouldBeTrue("d[0] == 0");
        shouldBeTrue("d[1] == 0");
        shouldBeTrue("d[2] == 0");
        shouldBeTrue("d[3] == 0");
    }

    function start() {
        debug("Check the imageBitmap of webgl.")
        var webgl_canvas = document.getElementById("webgl");
        var gl = webgl_canvas.getContext("webgl", {preserveDrawingBuffer: false});
        gl.clearColor(0.0, 1.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);
        createImageBitmapAndCheck(webgl_canvas, false).then(function() {
            runAfterLayoutAndPaint(asyncTest);
        });
    }

    function createImageBitmapAndCheck(webgl_canvas, discarded) {
        return createImageBitmap(webgl_canvas).then(function (imageBitmap) {
            ctx.clearRect(0, 0, 200, 200);
            ctx.drawImage(imageBitmap, 0, 0);
            if (!discarded) {
                shouldBeGreen(50, 50);
                shouldBeGreen(150, 150);
            } else {
                shouldBeTransparent(50, 50);
                shouldBeTransparent(150, 150);
            }
        }, function() {
            testFailed("Promise was rejected.");
            finishJSTest();
        });
    }

    function asyncTest() {
        debug("Check the imageBitmap of webgl in the next frame. drawingBuffer is discarded.")
        var webgl_canvas = document.getElementById("webgl");
        createImageBitmapAndCheck(webgl_canvas, true).then(function() {
            finishJSTest();
        });
    }
</script>
</body>
</html>
